package com.siyoumi.app.modules.sms.task;

import com.siyoumi.app.entity.SysSmsSend;
import com.siyoumi.app.modules.sms.service.SvcSms;
import com.siyoumi.app.service.SysSmsSendService;
import com.siyoumi.component.XApp;
import com.siyoumi.component.http.XHttpContext;
import com.siyoumi.config.SysConfig;
import com.siyoumi.mybatispuls.JoinWrapperPlus;
import com.siyoumi.task.EnumTask;
import com.siyoumi.task.TaskController;
import com.siyoumi.util.XDate;
import com.siyoumi.util.XReturn;
import com.siyoumi.util.XSqlStr;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

//发送短信
//http://dev.x.siyoumi.com/task/sms/task_sms_send
@RestController
@RequestMapping("/task/sms/task_sms_send")
public class TaskSmsSend
        extends TaskController {

    @Override
    protected Boolean handle1() {
        return false;
    }

    @Override
    protected List handleData() {
        JoinWrapperPlus<SysSmsSend> query = SysSmsSendService.getBean().join();
        query.eq("ssend_status", 0)
                .lt("ssend_status_date", XDate.now())
                .orderByAsc("ssend_create_date");
        int limit = 10;
        if (SysConfig.getIns().isDev()) {
            limit = 1;
        }
        query.last(XSqlStr.limitX(limit));

        return SysSmsSendService.getBean().get(query);
    }

    @Override
    protected void handleBefore(Object data) {
        SysSmsSend entity = (SysSmsSend) data;

        SysSmsSend entityUpdate = new SysSmsSend();
        entityUpdate.setSsend_id(entity.getKey());
        entityUpdate.setSsend_status_date(XDate.now().plusMinutes(3));
        SysSmsSendService.getBean().updateById(entityUpdate);
    }

    @Override
    protected XReturn handle(Object data) {
        SysSmsSend entity = (SysSmsSend) data;
        XHttpContext.setX(entity.getSsend_x_id());

        XApp.getTransaction().execute(status -> {
            return SvcSms.getBean().sendApi(entity.getSsend_id());
        });


        return EnumTask.RUN.getR();
    }
}
